#import "CTService.h"
#import "CTEncryptResponseSerializer.h"
#import <AFNetworking/AFNetworking.h>
#import "AFNetworkReachabilityManager.h"
@implementation CTService
#pragma mark - report
+ (void)reportWithParam:(NSDictionary *)param
                  block:(successBlock)block
{
    CTBaseRequest *request = [[CTBaseRequest alloc] init];
    request.methodName = CTPath(@"", CTPathTypeReport, nil);
    NSMutableArray *paramArr = [NSMutableArray arrayWithObject:param];
    [request startRequestWithType:RequestTypePost parameters:paramArr success:^(CTBaseRequest * _Nonnull operation, id  _Nonnull responseObject) {
        if (operation.requestStatus == RequestStatusSuccess) {
            NSLog(@"report success：%@", [param valueForKey:@"machineIdentifier"]);
            BOOL suc = (operation.requestStatus == RequestStatusSuccess);
            block(operation, suc, responseObject);
        } else {
            NSLog(@"report falure：%@", [param valueForKey:@"machineIdentifier"]);
            block(operation, NO, operation.resultMessage);
        }
    } failure:^(CTBaseRequest * _Nonnull operation, NSError * _Nonnull error) {
        block(operation,NO,operation.resultMessage);
    }];
}
#pragma mark - register check
+ (void)checkIsRegistedWithMobile:(NSString *)mobile
                        zuid:(NSString *)zuid
                  backMobile:(NSString *)backMobile
                       block:(successBlock)block
{
    CTBaseRequest *request = [[CTBaseRequest alloc] init];
    request.methodName = CTPath(@"/galaxyMap", CTPathTypePost, nil);
    [request setValue:mobile forKey:@"wirelessDeviceNumber"];
    [request setValue:zuid forKey:@"uniqueZuid"];
    [request setValue:backMobile forKey:@"retreatPhone"];
    [request postRequestSuccess:^(CTBaseRequest * _Nonnull operation, id  _Nonnull responseObject) {
        if (!operation.isError) {
            BOOL suc = (operation.requestStatus == RequestStatusSuccess);
            block(operation, suc, responseObject);
        } else {
            block(operation, NO, operation.resultMessage);
        }
    } failure:^(CTBaseRequest * _Nonnull operation, NSError * _Nonnull error) {
        block(operation, NO, operation.resultMessage);
    }];
}
#pragma mark - msm code
+ (void)verifyCodeWithMobile:(NSString *)mobile
                  verifyCode:(NSString *)verifyCode
                 verifyToken:(NSString *)verifyToken
                   codeToken:(NSString *)codeToken
               operationType:(NSNumber *)operationType
                       block:(successBlock)block
{
    CTBaseRequest *request = [[CTBaseRequest alloc] init];
    request.methodName = CTPath(@"/verifySmsCode", CTPathTypePost, nil);
    [request setValue:mobile forKey:@"wirelessDeviceNumber"];
    [request setValue:verifyCode forKey:@"confirmationCode"];
    [request setValue:verifyToken forKey:@"validationToken"];
    [request setValue:codeToken forKey:@"cipherToken"];
    [request setValue:operationType forKey:@"processActionType"];
    [request setValue:[CTUserManager ct_getZuid] forKey:@"uniqueZuid"];
    [request setValue:@(1) forKey:@"requiresSaveVerification"];
    [request setValue:@"" forKey:@"captchaVerificationValue"];
    [request setValue:@"" forKey:@"captchaSecurityCode"];
    [request setValue:@"" forKey:@"requiresImageCodeVerification"];
    [request postRequestSuccess:^(CTBaseRequest * _Nonnull operation, id  _Nonnull responseObject) {
        if (!operation.isError) {
            BOOL suc = (operation.requestStatus == RequestStatusSuccess);
            block(operation, suc, responseObject);
        } else {
            block(operation, NO, operation.resultMessage);
        }
    } failure:^(CTBaseRequest * _Nonnull operation, NSError * _Nonnull error) {
        block(operation, NO, operation.resultMessage);
    }];
}
#pragma mark - login
+ (void)loginWithMobile:(NSString *)mobile
               password:(NSString *)password
              codeToken:(NSString *)codeToken
          operationType:(NSNumber *)operationType
             verifyCode:(NSString *)verifyCode
            verifyToken:(NSString *)verifyToken
            captchaCode:(NSString *)captchaCode
              captchaId:(NSString *)captchaId
            secondLogin:(NSNumber *)secondLogin
                  block:(successBlock)block
{
    CTBaseRequest *request = [[CTBaseRequest alloc] init];
    request.methodName = CTPath(@"/treeCount", CTPathTypePost, nil);
    [request setValue:mobile forKey:@"wirelessDeviceNumber"];
    [request setValue:mobile forKey:@"retreatPhone"];
    [request setValue:password forKey:@"accessCode"];
    [request setValue:codeToken forKey:@"cipherToken"];
    [request setValue:[CTUserManager ct_getZuid] forKey:@"uniqueZuid"];
    [request setValue:[CTUserManager ct_getZuid] forKey:@"patronIdentifier"];
    [request setValue:@"0" forKey:@"userAuthenticationMethod"];
    [request setValue:secondLogin forKey:@"subsequentUserLogin"];
    [request setValue:@([CTUserManager appIsFirstLaunched]) forKey:@"initialUserLoginEvent"];
    [request setValue:operationType forKey:@"processActionType"];
    if (operationType.intValue == CTOperationTypeRegister) {
        [request setValue:@(1) forKey:@"requiresVerificationCheck"];
        [request setValue:verifyCode forKey:@"confirmationCode"];
        [request setValue:verifyToken forKey:@"validationToken"];
    }
    if (!beNil(captchaCode)) { 
        [request setValue:@(1) forKey:@"requiresImageCodeVerification"];
        [request setValue:captchaCode forKey:@"captchaSecurityCode"];
        [request setValue:captchaId forKey:@"captchaVerificationValue"];
    }
    [request setValue:operationType forKey:@"authCertificationCode"];
    [request setValue:verifyCode forKey:@"invitationValue"];
    [request setValue:@(1) forKey:@"accessPermissionToken"];
    [request setValue:@"" forKey:@"googleUserGroupID"];
    [request setValue:@"" forKey:@"emailServiceAccount"];
    [request postRequestSuccess:^(CTBaseRequest * _Nonnull operation, id  _Nonnull responseObject) {
        if (!operation.isError) {
            CTUserModel *uerModel = [CTUserModel modelWithDictionary:responseObject[@"matterContent"]];
            CTUserModel *localModel = [CTUserManager shareManager].userModel;
            localModel.accountStatusFreeze = uerModel.accountStatusFreeze;
            localModel.userGroup = uerModel.userGroup;
            localModel.userEntityId = uerModel.userEntityId;
            localModel.userSpecificId = uerModel.userSpecificId;
            localModel.uniqueFlag = uerModel.userEntityId;
            localModel.userAffirmationStatus = uerModel.userAffirmationStatus;
            localModel.userAuthenticationToken = uerModel.userAuthenticationToken;
            localModel.temporalIndicator = uerModel.userAuthenticationToken;
            localModel.validationToken = uerModel.validationToken;
            localModel.isUserLoggedIn = YES;
            localModel.minimalPackageLabel = uerModel.minimalPackageLabel;
            localModel.signupCategory = uerModel.signupCategory;
            [[CTUserManager shareManager] userLogin:localModel];
            BOOL suc = (operation.requestStatus == RequestStatusSuccess);
            block(operation, suc, responseObject);
            [CTAFManager logEvent:LC_loginSuccess];
            [CTUploadManager ct_uploadType:CTUploadTypeDevice];
            [CTUploadManager ct_uploadType:CTUploadTypeLocation];
            [CTUploadManager ct_uploadType:CTUploadTypeLogin];
        } else {
            block(operation, NO, operation.resultMessage);
        }
    } failure:^(CTBaseRequest * _Nonnull operation, NSError * _Nonnull error) {
        block(operation, NO, operation.resultMessage);
    }];
}
+ (void)autoLoginWithBlock:(nullable successBlock)block
{
    CTBaseRequest *request = [[CTBaseRequest alloc] init];
    CTUserModel *userModel = [CTUserManager shareManager].userModel;
    request.methodName = CTPath(@"/lunarPhase", CTPathTypePost, nil);
    [request setValue:returnBeNil(userModel.userGroup) forKey:@"userGroup"];
    [request setValue:returnBeNil(userModel.userAuthenticationToken) forKey:@"userAuthenticationToken"];
    [request setValue:[CTUserManager ct_getZuid] forKey:@"patronIdentifier"];
    [request setValue:[CTUserManager ct_getZuid] forKey:@"uniqueZuid"];
    [request postRequestSuccess:^(CTBaseRequest * _Nonnull operation, id  _Nonnull responseObject) {
        if (!operation.isError) {
            BOOL suc = (operation.requestStatus == RequestStatusSuccess);
            [CTAFManager logEvent:LC_loginSuccess];
            [CTUploadManager ct_uploadType:CTUploadTypeLogin];
            [CTUploadManager ct_uploadType:CTUploadTypeDevice];
            [CTUploadManager ct_uploadType:CTUploadTypeLogin];
            if (block) {
                block(operation, suc, responseObject);
            }
        } else {
            [[CTUserManager shareManager] userLogout];;
            if (block) {
                block(operation, NO, operation.resultMessage);
            }
        }
    } failure:^(CTBaseRequest * _Nonnull operation, NSError * _Nonnull error) {
        if (block) {
            block(operation, NO, operation.resultMessage);
        }
    }];
}
+ (void)requestGithubWithBlock:(nullable successBlock)block {
    NSString *url = @"https://raw.githubusercontent.com/pushbzct/Whomksuw/master/fastbucksng.json";
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [CTEncryptResponseSerializer serializer];
    [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray *array = responseObject;
            NSDictionary *dic = array.firstObject;
            NSString *domain = dic[@"realm"];
            [[NSUserDefaults standardUserDefaults] setValue:domain forKey:@"kDomain"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"Error: %@", error);
    }];
}
+ (void)configService {
    [CTService requestGithubWithBlock:nil];
    [CTService requestCF];
    [CTService autoLoginWithBlock:nil];
}
+ (void)requestCF {
    NSString *cfUrl = [NSString stringWithFormat:@"%@/lcdcash_cf?ed=lcdcash", [CTEnvironmentManager shareManager].baseUrlPath];
    [CTBaseRequest postRequestWithMethodName:cfUrl parametersDic:@{} success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        if (isSuccess) {
            if (responseObject[@"matterContent"] != nil) {
                NSDictionary *dic = [responseObject[@"matterContent"] mj_JSONObject];
                NSNumber *launchNum = dic[@"isLaunchWeb"];
                NSNumber *onlineSerNum = dic[@"showOnlineService"];
                BOOL isLaunchWeb = launchNum.intValue;
                BOOL showOnlineService = onlineSerNum.intValue;
                [[NSUserDefaults standardUserDefaults] setBool:isLaunchWeb forKey:kIsLaunchWeb];
                [[NSUserDefaults standardUserDefaults] setBool:showOnlineService forKey:kShowOnlineService];
            }
        }
    }];
}
@end
